package com.chat.demo.userservice;

import com.chat.demo.userservice.DTO.Group.UserJoinedRoomDTO;
import com.chat.demo.userservice.Entity.DAO.ChatRoomMapper;
import com.chat.demo.userservice.Entity.DAO.UserChatRoomDao;
import com.chat.demo.userservice.Entity.Entity.ChatRoom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ChatRoom_Service {
    @Autowired
    private ChatRoomMapper mapper;
    @Autowired
    private UserChatRoomDao userChatRoomDao;

    public Long createRoom(ChatRoom room) {
        int result = mapper.createRoom(room);
        if (result > 0) {
            return room.getRoomId();
        }
        return -1L;
        // return mapper.createRoom(room);
    }

    public List<UserJoinedRoomDTO> getJoinedRoomsByUserId(Long userId) {
        return userChatRoomDao.getJoinedRoomsByUserId(userId);
    }

    public List<Long> getRoomIdsByUserId(int userId) {
        return mapper.getRoomIdsByUserId(userId);
    }

    public boolean deleteRoom(int roomId, int userId) {
        if (mapper.isCreator(roomId, userId) || mapper.isAdmin(roomId, userId)) {
            return mapper.deleteRoom(roomId) > 0;
        }
        return false;
    }

    public boolean inviteUser(int roomId, int inviterId, int targetUserId, String role) {
        if (mapper.isAdmin(roomId, inviterId)) {
            return mapper.inviteUser(targetUserId, roomId, role) > 0;
        }
        return false;
    }

    public boolean updateUserRole(int roomId, int adminId, int targetUserId, String role) {
        if (mapper.isAdmin(roomId, adminId)) {
            return mapper.updateUserRole(targetUserId, roomId, role) > 0;
        }
        return false;
    }

    public boolean removeUser(int roomId, int adminId, int targetUserId) {
        if (mapper.isAdmin(roomId, adminId)) {
            return mapper.removeUser(targetUserId, roomId) > 0;
        }
        return false;
    }

    public boolean joinRoom(int roomId, int userId) {
        return mapper.joinRoom(userId, roomId) > 0;
    }

    public boolean leaveRoom(int roomId, int userId) {
        return mapper.leaveRoom(userId, roomId) > 0;
    }
}
